<template>
  <px-dialog v-model="visible" :title="title" @close="cancel">
    <px-form ref="formRef" v-loading="loading" :model="formParams" :rules="rules" :validate-on-rule-change="false" inline label-width="100px">
      <px-row>
        <px-col :span="12">
          <px-form-item label="证照类型" prop="type">
            <px-select v-model="formParams.type" clearable filterable placeholder="请选择" style="width: 100%" @change="handleTypeChange">
              <px-option v-for="item in certificateTypeList" :key="item.licenseCategoryId" :label="item.category" :value="item.licenseCategoryId" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="科室" prop="className">
            <px-select v-model="formParams.className" clearable filterable placeholder="请选择" style="width: 100%">
              <px-option v-for="item in classNameList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="证照名称" prop="name">
            <!-- <px-input v-model="formParams.name" placeholder="请输入" maxLength="50" clearable style="width: 100%" /> -->
            <px-select v-model="formParams.name" placeholder="请选择证照名称" style="width: 100%" clearable>
              <px-option v-for="item in nameList" :key="item.value" :label="item.name" :value="item.name" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="颁证机构" prop="department">
            <px-input v-model="formParams.department" placeholder="请输入" maxLength="50" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="颁证日期" prop="date">
            <px-date-picker
              v-model="formParams.date"
              type="date"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择"
              style="width: 100%"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="有效期至" prop="validity">
            <px-date-picker
              v-model="formParams.validity"
              type="date"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择"
              style="width: 100%"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="12">
          <px-form-item label="办证时间(天)" prop="duration">
            <!-- <px-date-picker
              v-model="formParams.duration"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            /> -->
            <px-input-number v-model="formParams.duration" placeholder="请输入" :min="1" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.categoryType === 'DEVICE'" :span="12">
          <px-form-item label="设备编码" prop="equipNo">
            <!-- <px-select-v2
              v-model="formParams.equipNo"
              filterable
              :options="typeIdList"
              placeholder="请选择设备编码"
              @focus="handleTypeFocus"
              @change="handleTypeChange"
            /> -->
            <px-select-v2
              v-model="formParams.equipNo"
              style="width: 100%"
              filterable
              clearable
              :options="typeIdList"
              placeholder="请选择"
              @change="changeEqpNo"
            />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.categoryType === 'CERT'" :span="12">
          <px-form-item label="持证人" prop="holder">
            <px-select v-model="formParams.holder" clearable filterable placeholder="请选择" style="width: 100%" @change="changeHolder">
              <px-option v-for="item in personList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col v-if="activeTab.categoryType === 'DEVICE'" :span="12">
          <px-form-item label="设备名称" prop="equipName">
            <px-input v-model="formParams.equipName" placeholder="请选择设备编码" disabled clearable style="width: 100%" />
            <!-- <px-select-v2 v-model="formParams.equipName" filterable disabled :options="modelIdList" placeholder="请选择" style="width: 100%" /> -->
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.categoryType === 'CERT'" :span="12">
          <px-form-item label="组织" prop="organization">
            <px-input v-model="formParams.organization" placeholder="请输入" clearable style="width: 100%" :readonly="handleType === 'EDIT'" />
          </px-form-item>
        </px-col>
        <px-col v-if="activeTab.categoryType === 'CERT'" :span="12">
          <px-form-item label="手机号" prop="tel">
            <px-input v-model="formParams.tel" placeholder="请输入" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row v-if="activeTab.categoryType === 'CERT'">
        <px-col :span="12">
          <px-form-item label="身份证号" prop="idNumber">
            <px-input v-model="formParams.idNumber" placeholder="请输入" clearable style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="24">
          <px-form-item label="证照附件" prop="pic">
            <FileUpload
              fileType="add"
              fileAccept="'pdf','png', 'jpg', 'jpeg', 'gif', 'bmp','webp'"
              :fileData="{ moduleName: 'eqp' }"
              :fileSize="fileSize"
              :fileList="fileList"
              :multiple="multiple"
              fileBtnText="上传文件"
              tipText="文件"
              @changeFileList="changeFileList"
            />
          </px-form-item>
        </px-col>
      </px-row>
      <px-row>
        <px-col :span="24">
          <px-form-item label="备注" prop="remark">
            <px-input v-model="formParams.remark" placeholder="请输入" maxLength="200" clearable :rows="4" type="textarea" style="width: 100%" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template v-if="handleType !== 'VIEW'" #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="save">保存</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup>
import { computed, ref, reactive, toRefs, onMounted } from "vue";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getPersonListAPI } from "@/api/knowledge/documentManage";
import { editSearchAPI, saveCertificateAPI, getEqpListAPI, licenseNameSelectsAPI } from "@/api/knowledge/certificate";
import { PxMessage, PxMessageBox } from "px-ui";
import { getEquipModelSelect, getEquipTypeSelect } from "@/api/equip/archive";
import { getToken } from "@/utils/auth";
import FileUpload from "@/components/Upload/FileUpload.vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ""
  },
  certificateTypeList: {
    type: Array,
    default: () => []
  },
  classNameList: {
    type: Array,
    default: () => []
  },
  handleType: {
    type: String,
    default: ""
  },
  activeTab: {
    type: Object,
    default: () => {}
  },
  rowData: {
    type: Object,
    default: () => {}
  },
  // 文档上传接口url
  actionUrl: {
    type: String,
    default: "/ifp/sharing/api/v1/file/upload",
    required: false
  }
});
const emits = defineEmits(["update:visible", "saveAction"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);
const nameList = ref([]);

const state = reactive({
  loading: false,
  formParams: {
    pic: []
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  personList: [],
  typeIdList: [], // 设备编码下拉框
  modelIdList: [] // 设备名称下拉框
});

const fileList = ref([]);
const fileUploadList = ref([]);
const fileSize = ref(999);
const fileType = ref("add");
const multiple = ref(true);
const { loading, formParams, headers, personList, typeIdList, modelIdList } = toRefs(state);

const rules = computed(() => ({
  type: [{ required: true, message: "证照类型不能为空", trigger: "change" }],
  className: [{ required: true, message: "科室不能为空", trigger: "change" }],
  name: [{ required: true, message: "证照名称不能为空", trigger: "blur" }],
  holder: [{ required: true, message: "持证人不能为空", trigger: "change" }],
  tel: [{ required: false }, { pattern: /^1[3456789]\d{9}$/, message: "手机号格式错误", trigger: "blur" }],
  idNumber: [{ required: false }, { pattern: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/, message: "身份证号格式错误", trigger: "blur" }]
}));

onMounted(() => {
  if (props.handleType !== "ADD") {
    editSearch();
  }
  getPersonList();
  getEqpList();
});

// 获取证照名称下拉框数据
const getNameList = async () => {
  try {
    let params = {
      categoryId: null,
      licenseCategoryId: state?.formParams?.type || null
    };
    nameList.value = await licenseNameSelectsAPI(params);
  } catch (error) {}
};

const changeFileList = val => {
  fileUploadList.value = val.map(item => {
    return {
      id: item.id,
      originalName: item.originalName,
      fileName: item.fileName,
      fileType: item.fileType,
      fileSize: item.fileSize,
      fileUrl: item.fileUrl,
      accountId: item.accountId,
      accountName: item.accountName,
      status: item.status,
      createTime: item.createTime,
      updateTime: item.updateTime
    };
  });
};

const getPersonList = async () => {
  state.personList = await getPersonListAPI();
  state.personList.forEach(item => {
    item.id = item.userId;
    item.name = `${item.empNo}-${item.realName}`;
    item.value = `${item.userId}-${item.empNo}-${item.realName}`;
  });
};

const getEqpList = async () => {
  try {
    state.loading = true;
    const res = await getEqpListAPI({});
    state.typeIdList = res.map(item => ({ id: item.id, value: item.eqpId, label: item.eqpId, eqpId: item.eqpId, eqpName: item.eqpName }));
    state.modelIdList = res.map(item => ({ id: item.id, value: item.eqpName, label: item.eqpName, eqpId: item.eqpId, eqpName: item.eqpName }));
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const changeEqpNo = val => {
  state.formParams.equipName = state.modelIdList.find(item => item.eqpId === val)?.label;
};

const cancel = () => {
  emits("update:visible", false);
};

// 新的图片列表
const changePhotoList = val => {
  state.formParams.pic = val;
};

// 查询证照信息
const editSearch = async () => {
  try {
    state.loading = true;
    const res = await editSearchAPI({ id: props.rowData.id });
    state.formParams = {
      type: res.licenseCategoryId,
      className: res.department,
      name: res.name,
      equipNo: res.deviceCode,
      equipName: res.deviceName,
      department: res.institution,
      date: res.releaseTime,
      validity: res.dueTime,
      // duration: [res.durationStartTime, res.durationEndTime],
      duration: res.durationPeriod,
      pic: res.documentId,
      holder: res.holder,
      tel: res.mobile,
      organization: res.org,
      remark: res.remark
    };
    fileList.value = res?.documentId ? res.documentId : [];
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const changeHolder = val => {
  const person = state.personList.find(item => item.value === val);
  state.formParams.organization = person?.deptName;
  state.formParams.tel = person?.phone || "";
};

const submitForm = async () => {
  try {
    state.loading = true;
    // const pic = state.formParams.pic[0]?.response ? state.formParams.pic?.map(item => item.response.data) : state.formParams.pic;
    const params = {
      id: props.handleType === "EDIT" ? props.rowData.id : "",
      categoryId: props.activeTab.categoryId,
      // categoryParentId: 0,
      licenseCategoryId: state.formParams.type,
      department: state.formParams.className,
      name: state.formParams.name,
      // deviceCode: typeIdList.value.filter(item => item.value === state.formParams.equipNo)[0]?.label,
      // deviceName: modelIdList.value.filter(item => item.value === state.formParams.equipName)[0]?.label,
      institution: state.formParams.department,
      releaseTime: state.formParams.date,
      dueTime: state.formParams.validity,
      // durationStartTime: state.formParams.duration[0] ?? "",
      // durationEndTime: state.formParams.duration[1] ?? "",
      durationPeriod: state.formParams.duration,
      documentId: props.handleType === "EDIT" ? fileList.value : fileUploadList.value,
      // holder: state.formParams.holder,
      // org: state.formParams.organization,
      // idCard: state.formParams.idNumber,
      // mobile: state.formParams.tel,
      state: props.rowData.state,
      remark: state.formParams.remark
    };
    // 设备证照
    if (props?.activeTab?.categoryType === "DEVICE") {
      params.deviceCode = typeIdList.value.filter(item => item.value === state.formParams.equipNo)[0]?.label;
      params.deviceName = modelIdList.value.filter(item => item.value === state.formParams.equipName)[0]?.label;
    }
    // 人员证照
    if (props?.activeTab?.categoryType === "CERT") {
      params.holder = state.formParams.holder;
      params.mobile = state.formParams.tel;
      params.org = state.formParams.organization;
      params.idCard = state.formParams.idNumber;
    }
    await saveCertificateAPI(params);
    emits("update:visible", false);
    emits("saveAction");
    PxMessage.success("保存成功");
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 保存
const save = () => {
  formRef.value.validate(valid => {
    if (valid) {
      submitForm();
    }
  });
};

const handleTypeChange = () => {
  state.formParams.name = "";
  getNameList();
};
</script>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;
}

.upload-demo {
  width: 100%;
}
</style>
